import serial
import time
import binascii
from datetime import datetime
import threading

# 设置串口参数
port = "/dev/ttySC0"  # 根据你的系统和串口适配器来设置串口名称
baud_rate = 38400  # 波特率

# 打开串口
ser = serial.Serial(port, baud_rate, timeout=1)

exit_flag = 0  # 设置退出标志，0表示不退出


def send_and_read_485(command):
    try:
        # 发送指令
        hex_str = bytes.fromhex(command)
        ser.write(hex_str)

        # 记录发送时间
        send_time = time.time()

        # # 初始化回复数据
        # response = b""
        #
        # # 设置一个超时时间，单位为秒
        # timeout = 5  # 例如，设置为 5 秒
        #
        # while True:
        #     data = ser.read(1)  # 逐字节读取
        #     response += data
        #     if not data or time.time() - send_time > timeout:
        #         break
        #         str1 = binascii.b2a_hex(s.read(n))
        # # 记录接收时间
        # receive_time = time.time()
        #
        # # 计算时间间隔
        # time_interval = receive_time - send_time

        send_time = datetime.fromtimestamp(send_time).strftime("%Y-%m-%d %H:%M:%S.%f")
        # receive_time = datetime.fromtimestamp(receive_time).strftime("%Y-%m-%d %H:%M:%S.%f")

        print(f"发送时间：{send_time}")
        # print(f"接收时间：{receive_time}")
        # print(f"时间间隔：{time_interval} 秒")
        # print(f"回复内容：{binascii.b2a_hex(response).decode()}")

    except Exception as e:
        print(f"发生错误：{e}")

    finally:
        # 关闭串口
        ser.flushInput()


def recv():  # 接收串口信息
    global exit_flag
    timeout = 5  # 超时时间（秒）
    start_time = time.time()  # 记录开始时间
    while not exit_flag:
        if time.time() - start_time > timeout:
            return b''  # 超时，返回空数据

        time.sleep(0.5)
        data = ser.read_all()
        if data != b'':
            return data  # 有数据可用，返回数据


def serial_read():  # 接收串口信息
    global exit_flag
    print("接收串口信息启动")
    while not exit_flag:
        data = recv()
        # 转换为十六进制字节流
        # s_hex = binascii.hexlify(data)
        # # 字节流转换成字符串
        # s_hex = bytes.decode(s_hex)

        receive_time = time.time()
        receive_time = datetime.fromtimestamp(receive_time).strftime("%Y-%m-%d %H:%M:%S.%f")
        print(f"接收时间：{receive_time}")
        print(f"回复内容：{data}")


# 执行线程2
thread2 = threading.Thread(target=serial_read)
thread2.start()

# 重复执行线程
for _ in range(3):  # 重复3次，可以根据需要调整
    time.sleep(2)
    thread1 = threading.Thread(target=send_and_read_485, args=("010600000001480A",))
    thread3 = threading.Timer(0.5, send_and_read_485, args=("01060000000089CA",))

    thread1.start()
    thread3.start()

    thread1.join()
    thread3.join()

time.sleep(5)
exit_flag = 1  # 设置退出标志，1表示退出
thread2.join()

# 接收串口信息启动
# 发送时间：2023-10-31 15:37:23.514795
# 发送时间：2023-10-31 15:37:23.715449

# 接收时间：2023-10-31 15:37:24.015398
# 回复内容：01060000000089ca
# 发送时间：2023-10-31 15:37:25.719321
# 发送时间：2023-10-31 15:37:25.945468
# 接收时间：2023-10-31 15:37:26.018658
# 回复内容：01060000000089ca
# 发送时间：2023-10-31 15:37:27.952929
# 接收时间：2023-10-31 15:37:28.021851
# 回复内容：010600000001480a
# 发送时间：2023-10-31 15:37:28.154114
# 接收时间：2023-10-31 15:37:28.523067
# 回复内容：01060000000089ca
# Exception in thread Thread-1:
# Traceback (most recent call last):
#   File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner
#     self.run()
#   File "/usr/lib/python3.9/threading.py", line 892, in run
#     self._target(*self._args, **self._kwargs)
#   File "/home/pi/use/aaa.py", line 79, in serial_read
#     s_hex = binascii.hexlify(data)
